﻿using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace NCT.MRS.PresentationLayer
{
    public static class MethodExtension
    {
        public static void UpdateRelatedEntities<TSource, TTarget>(this DataServiceContext entities,
    TSource source,
    Expression<Func<DataServiceCollection<TTarget>>> collectionProperty,
    IEnumerable<TTarget> newRelatedEntities)
        {
            var memberExpression = collectionProperty.Body as MemberExpression;
            string collectionName = memberExpression.Member.Name;
            var sourceProperty = source.GetType().GetProperty(collectionName).GetValue(source, null) as IEnumerable<TTarget>;
            foreach (var genre in sourceProperty)
            {
                if (!newRelatedEntities.Contains(genre))
                {
                    //movie.Genres.Remove(genre); 
                    entities.DeleteLink(source, collectionName, genre);
                }
            }
            //movie.Genres.Clear(); 
            foreach (var newGenre in newRelatedEntities)
            {
                if (!sourceProperty.Contains(newGenre))
                {
                    //movie.Genres.Add(newGenre); 
                    entities.AddLink(source, collectionName, newGenre);
                }
            }
        }
    }
}
